package org.gateway.server.predicate;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;

import lombok.Data;
import lombok.NoArgsConstructor;

@Component
public class ParamRoutePredicateFactory extends AbstractRoutePredicateFactory<ParamRoutePredicateFactory.Config> {

	public ParamRoutePredicateFactory() {
		super(ParamRoutePredicateFactory.Config.class);
	}
	
	@Override
    public List<String> shortcutFieldOrder() {
		return Arrays.asList(new String[] {"param1", "param2"});
    }

	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return new GatewayPredicate() {
			@Override
			public boolean test(ServerWebExchange serverWebExchange) {
				// 获取请求参数 msg，判断是否匹配 param1、param2
	            String param = serverWebExchange.getRequest().getQueryParams().getFirst("msg");
	            if (ObjectUtils.isEmpty(param)) {
	                return false;
	            }
	            if (param.equals(config.getParam1()) || param.equals(config.getParam2())) {
	            	return true;
	            }
				return false;
			}
		};
	}

    @Data
    @NoArgsConstructor
    public static class Config {
        private String param1;
        private String param2;
    }
}
